package main.UI;

import main.UI.misc.ErrorHandling;
import main.database.DatabaseException;
import main.database.SQLDatabaseManager;
import main.database.entity.Category;
import main.database.entity.MyEntity;
import main.database.entity.Product;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;

public class ProductDialog extends JDialog {
    private JPanel contentPane;
    private JButton buttonOK;
    private JButton buttonCancel;
    private JTextField nameField;
    private JTable table;

    private String formerName;
    private Long changedEntryID;
    private DefaultTableModel tableModel = new DefaultTableModel() {

        @Override
        public boolean isCellEditable(int row, int column) {
            return false;
        }
    };

    private static final Color ERROR_BACKGROUND_COLOR = new Color( 255, 215, 215 );

    //private JTextField categoryField;
    //private JButton catButton;
    //private ProductDialog thisDialog = this;
    private SQLDatabaseManager mngr = GUI.getSQLManager();

    public ProductDialog (Long id, String name, String cat) throws DatabaseException{
        this();
        changedEntryID = id;
        nameField.setText(name);
        formerName = name;
        for (int rowCnt = 0; rowCnt < table.getRowCount(); rowCnt++) {
            if (table.getValueAt(rowCnt, 0).equals(cat)) {
                table.setRowSelectionInterval(rowCnt, rowCnt);
                break;
            }
        }
        setTitle("Изменить товар");
    }

    public ProductDialog() throws DatabaseException{
        /*parentDialog = dlg;*/
        formerName = "";
        changedEntryID = (long) 0;
        setContentPane(contentPane);
        setModalityType(DEFAULT_MODALITY_TYPE);
        getRootPane().setDefaultButton(buttonOK);
        setResizable(false);
        setTitle("Новый товар");

       /* catButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                SelectEntryDialog categoryDialog = new SelectEntryDialog(GUI.getSQLManager(), thisDialog,
                        SelectDialogType.SELECT_CATEGORY_DIALOG, false);
                GUI.centerDialog(categoryDialog);
                categoryDialog.pack();
                categoryDialog.setVisible(true);
            }
        });*/

        nameField.getDocument().addDocumentListener(new DocumentListener() {
            public void changedUpdate(DocumentEvent e) {
                updateColor(nameField);
            }
            public void removeUpdate(DocumentEvent e) {
                updateColor(nameField);
            }
            public void insertUpdate(DocumentEvent e) {
                updateColor(nameField);
            }
        });

        table.setModel(tableModel);
        table.setRowHeight(20);

        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        tableModel.addColumn("Наименование");
        tableModel.addRow(new Object[] {"Без категории"});
        table.setTableHeader(null);

        Action enterAction = new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                buttonOK.doClick(50);
            }
        };

        table.getInputMap().put(KeyStroke.getKeyStroke("released ENTER"),
                "enterReleased");
        table.getActionMap().put("enterReleased", enterAction);

        List categoryList = mngr.getAllEntriesFromDB(MyEntity.CATEGORY);

        for (Object aCategory : categoryList) {
            Category cat = (Category) aCategory;
            addNewTableEntry(cat.getName());
        }

        table.setRowSelectionInterval(0, 0);

        buttonOK.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onOK();
            }
        });

        buttonCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        });

// call onCancel() when cross is clicked
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });
    }


    private void onOK() {
        if (nameField.getText().trim().equals("")){
            ErrorHandling.showError(null, "Имя продукта не может быть пустым", false);
            nameField.setBackground(ERROR_BACKGROUND_COLOR);
            return;
        }
        try {
        if (changedEntryID!=0) {
            if (!changeProduct())
                return;
            }
            else {
            if (!addProduct())
                return;
            }
        }
        catch (DatabaseException e) {
            ErrorHandling.showError(e, "Ошибка при обращении к базе данных", false);
        }
        finally {
            dispose();
        }
    }

    private void onCancel() {
// add your code here if necessary
        dispose();
    }

    private boolean addProduct() throws DatabaseException{
        String name = nameField.getText();

        if (mngr.getIDByName(MyEntity.PRODUCT, name) == 0)
        {
            String catName = (String) table.getValueAt(table.getSelectedRow(), 0);
            Product product = mngr.saveProduct(name, catName, (long) 0);
            GUI.addNewProduct(product.getId(), name, catName);
            return true;
        }
        else {
            duplicateError();
            return false;
        }
    }

    private boolean changeProduct() throws DatabaseException{
        String name = nameField.getText();
        if (!name.equals(formerName) && mngr.getIDByName(MyEntity.PRODUCT, name) > 0) {
            duplicateError();
            return false;
        }
        else
        {
            String catName = (String) table.getValueAt(table.getSelectedRow(), 0);
            mngr.saveProduct(name, catName, changedEntryID);
            GUI.changeProductEntry(name, catName);
            return true;
        }
    }

    private void duplicateError() {
        JOptionPane.showMessageDialog(null, "Запись с таким именем уже существует", "Ошибка", JOptionPane.ERROR_MESSAGE);
        nameField.setBackground(ERROR_BACKGROUND_COLOR);
    }

    private void addNewTableEntry(String name) {
        tableModel.addRow(new Object[]{name});
    }

    private void updateColor(Component cmp) {
        cmp.setBackground(null);
    }
}